/* eslint-disable no-plusplus */
import { renderInputDropdownItem } from './render'
import { findFilterItemByValue } from './util'
import { defaults } from './config'

function renderHistroyItem(item) {
  return renderInputDropdownItem({
    name: item.name,
    class: 'history-item',
    key: '<cmd:apply:' + escape(JSON.stringify(item.value)) + '>'
  })
}

export class History {
  constructor(config) {
    if (typeof config === 'object') {
      $.extend(this, defaults.history, config)
    } else {
      $.extend(this, defaults.history)
    }
  }

  load() {
    try {
      const data = JSON.parse(this.store.getItem(this.storeKey))
      if (data instanceof Array) {
        return data
      }
    } catch (e) {
      return []
    }
    return []
  }

  generateItem(filters, data) {
    let name = []

    // 生成条件组名称
    filters.forEach((filter) => {
      const value = data[filter.key]

      if (!value) {
        return
      }
      if (filter.none && value.toString() === filter.none.value.toString()) {
        name.push(filter.name + ': ' + filter.none.name)
        return
      }
      if (filter.multiple && value instanceof Array) {
        const values = []

        value.forEach((v) => {
          const item = findFilterItemByValue(filter, v)
          if (item) {
            values.push(item.name)
          }
        })
        if (values.length > 0) {
          name.push(filter.name + ': ' + values.join(', '))
        }
        return
      }
      if (filter.type === 'daterange') {
        name.push(filter.name + ': ' + value)
        return
      }

      const item = findFilterItemByValue(filter, value)

      if (item) {
        name.push(filter.name + ': ' + item.name)
      }
    })

    if (data.search) {
      name.push(data.search)
    }
    if (name.length < 1) {
      return false
    }
    name = name.join('; ')
    return { name: name, value: data }
  }

  /**
   * 添加历史记录
   * @param {Array} filters 筛选器列表，用于为条件组生成名称
   */
  add(filters, data) {
    let history = this.load()
    const item = this.generateItem(filters, data)
    // 删除同名的历史记录
    for (let i = 0; i < history.length; ++i) {
      if (history[i].name === item.name) {
        history.splice(i, 1)
        break
      }
    }
    history.splice(0, 0, item)
    history = history.splice(0, this.limit)
    this.store.setItem(this.storeKey, JSON.stringify(history))
    return true
  }

  clear() {
    this.store.removeItem(this.storeKey)
  }

  render() {
    const html = []
    const history = this.load()

    history.forEach(function (item) {
      html.push(renderHistroyItem(item))
    })
    return html.join('')
  }
}

export default History
